using Microsoft.EntityFrameworkCore;
using RAG.Domain.Entities.App;
using RAG.Domain.Repositories;
using RAG.Infrastructure.Data;

namespace RAG.Infrastructure.Repositories;

public class DocumentRepository : IDocumentRepository
{
    private readonly RagAIDbContext _context;

    public DocumentRepository(RagAIDbContext context)
    {
        _context = context;
    }

    public async Task<Documents> CreateAsync(Documents document)
    {
        _context.Documents.Add(document);
        await _context.SaveChangesAsync();
        return document;
    }

    public async Task<Documents?> GetByIdAsync(Guid id)
    {
        return await _context.Documents
            .Include(d => d.DocumentChunks)
            .ThenInclude(c => c.KnowledgeBase)
            .FirstOrDefaultAsync(d => d.Id == id);
    }

    public async Task<List<Documents>> GetAllAsync()
    {
        return await _context.Documents
            .Include(d => d.DocumentChunks)
            .OrderByDescending(d => d.CreatedAt)
            .ToListAsync();
    }

    public async Task<List<Documents>> GetByUserIdAsync(Guid userId)
    {
        return await _context.Documents
            .Include(d => d.DocumentChunks)
            .Where(d => d.CreatedBy == userId)
            .OrderByDescending(d => d.CreatedAt)
            .ToListAsync();
    }

    public async Task<Documents> UpdateAsync(Documents document)
    {
        document.UpdatedAt = DateTime.UtcNow;
        _context.Documents.Update(document);
        await _context.SaveChangesAsync();
        return document;
    }

    public async Task DeleteAsync(Guid id)
    {
        var document = await _context.Documents.FindAsync(id);
        if (document != null)
        {
            _context.Documents.Remove(document);
            await _context.SaveChangesAsync();
        }
    }
}
